#include "treasureWidget.h"

TreasureWidget::TreasureWidget(QWidget* p):QWidget(p),ui(new Ui::TreasureWidget),filePath("")
{
    ui->setupUi(this);
    setInputMask();

    connect(ui->treeWidget_treasure_fragment,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(s_fragmentItemDoubleClicked(QTreeWidgetItem*,int)));
    connect(ui->tableWidget_treasure_fragment,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(s_cellDoubleClicked(int,int)));
}

TreasureWidget::~TreasureWidget()
{
    delete ui;
}

void TreasureWidget::setInputMask()
{
    QIntValidator* charValidator = new QIntValidator(-128,127,this);

    ui->lineEdit_treasure_maxAtkAddonMin->setValidator(charValidator);
    ui->lineEdit_treasure_maxAtkAddonMax->setValidator(charValidator);
    ui->lineEdit_treasure_minAtkAddonMin->setValidator(charValidator);
    ui->lineEdit_treasure_minAtkAddonMax->setValidator(charValidator);
    ui->lineEdit_treasure_maxDefAddonMin->setValidator(charValidator);
    ui->lineEdit_treasure_maxDefAddonMax->setValidator(charValidator);
    ui->lineEdit_treasure_minDefAddonMin->setValidator(charValidator);
    ui->lineEdit_treasure_minDefAddonMax->setValidator(charValidator);
    ui->lineEdit_treasure_maxAtkProAddonMin->setValidator(charValidator);
    ui->lineEdit_treasure_maxAtkProAddonMax->setValidator(charValidator);
    ui->lineEdit_treasure_maxDefProAddonMin->setValidator(charValidator);
    ui->lineEdit_treasure_maxDefProAddonMax->setValidator(charValidator);
}

Treasure TreasureWidget::getTreasureFromUI()
{
    Treasure t;

    t.id = (qint32) ui->lineEdit_treasure_id->text().toInt();
    t.name = ui->lineEdit_treasure_name->text();
    t.description = ui->plainTextEdit_treasure_description->toPlainText();
    t.max_attack_addon_min = (qint8)ui->lineEdit_treasure_maxAtkAddonMin->text().toInt();
    t.max_attack_addon_max = (qint8)ui->lineEdit_treasure_maxAtkAddonMax->text().toInt();
    t.min_attack_addon_min = (qint8)ui->lineEdit_treasure_minAtkAddonMin->text().toInt();
    t.min_attack_addon_max = (qint8)ui->lineEdit_treasure_minAtkAddonMax->text().toInt();
    t.max_defense_addon_min = (qint8)ui->lineEdit_treasure_maxDefAddonMin->text().toInt();
    t.max_defense_addon_max = (qint8)ui->lineEdit_treasure_maxDefAddonMax->text().toInt();
    t.min_defense_addon_min = (qint8)ui->lineEdit_treasure_minDefAddonMin->text().toInt();
    t.min_defense_addon_max = (qint8)ui->lineEdit_treasure_minDefAddonMax->text().toInt();
    t.max_attack_probability_min = (qint8)ui->lineEdit_treasure_maxAtkProAddonMin->text().toInt();
    t.max_attack_probability_max = (qint8)ui->lineEdit_treasure_maxAtkProAddonMax->text().toInt();
    t.max_defense_probability_min = (qint8)ui->lineEdit_treasure_maxDefProAddonMin->text().toInt();
    t.max_defense_probability_max = (qint8)ui->lineEdit_treasure_maxDefProAddonMax->text().toInt();

    int cnt = 0;
    while(ui->tableWidget_treasure_fragment->item(cnt,1))
    {
        if(ui->tableWidget_treasure_fragment->item(cnt,1)->text().replace(" ","").isEmpty())
            break;
        cnt++;
    }
    t.needed_Fragments_count = (qint32)cnt;
    if(cnt>0)
    {
        t.needed_Fragments = new NeededFragment[cnt];
        for(int i=0;i<cnt;i++)
        {
            if(ui->tableWidget_treasure_fragment->item(i,1))
                t.needed_Fragments[i].id = (qint32) ui->tableWidget_treasure_fragment->item(i,1)->text().toInt();
            else
                t.needed_Fragments[i].id = 0;
            if(ui->tableWidget_treasure_fragment->item(i,2))
                t.needed_Fragments[i].count = (qint8) ui->tableWidget_treasure_fragment->item(i,2)->text().toInt();
            else
                t.needed_Fragments[i].id = 0;
        }
    }else
        t.needed_Fragments = 0;

    return t;
}

void TreasureWidget::displayTreasureToUI(Treasure& t)
{
    clearUI();

    ui->lineEdit_treasure_id->setText(QString::number(t.id));
    ui->lineEdit_treasure_name->setText(t.name);
    ui->plainTextEdit_treasure_description->setPlainText(t.description);

    ui->lineEdit_treasure_maxAtkAddonMin->setText(QString::number(t.max_attack_addon_min));
    ui->lineEdit_treasure_maxAtkAddonMax->setText(QString::number(t.max_attack_addon_max));
    ui->lineEdit_treasure_minAtkAddonMin->setText(QString::number(t.min_attack_addon_min));
    ui->lineEdit_treasure_minAtkAddonMax->setText(QString::number(t.min_attack_addon_max));
    ui->lineEdit_treasure_maxDefAddonMin->setText(QString::number(t.max_defense_addon_min));
    ui->lineEdit_treasure_maxDefAddonMax->setText(QString::number(t.max_defense_addon_max));
    ui->lineEdit_treasure_minDefAddonMin->setText(QString::number(t.min_defense_addon_min));
    ui->lineEdit_treasure_minDefAddonMax->setText(QString::number(t.min_defense_addon_max));
    ui->lineEdit_treasure_maxAtkProAddonMin->setText(QString::number(t.max_attack_probability_min));
    ui->lineEdit_treasure_maxAtkProAddonMax->setText(QString::number(t.max_attack_probability_max));
    ui->lineEdit_treasure_maxDefProAddonMin->setText(QString::number(t.max_defense_probability_min));
    ui->lineEdit_treasure_maxDefProAddonMax->setText(QString::number(t.max_defense_probability_max));

    int cnt = t.needed_Fragments_count;
    for(int i=0;i<cnt;i++)
    {
        ui->tableWidget_treasure_fragment->setItem(i,0,new QTableWidgetItem((QString)fragmentMap.value((int)t.needed_Fragments[i].id)));
        ui->tableWidget_treasure_fragment->setItem(i,1,new QTableWidgetItem(QString::number(t.needed_Fragments[i].id)));
        ui->tableWidget_treasure_fragment->setItem(i,2,new QTableWidgetItem(QString::number(t.needed_Fragments[i].count)));
    }
}

Treasure TreasureWidget::readTreasureFromFile()
{
    Treasure t;

    QFile f(filePath);
    if(f.exists())
    {
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>t;
        displayTreasureToUI(t);
        f.close();
    }else
        WARNING_FILE_NOT_EXIST;

    return t;
}

bool TreasureWidget::saveTreasureToFile()
{
    if(ui->lineEdit_treasure_name->text().isEmpty()||filePath.isEmpty())
    {
        WARNING_NO_NAME;
        return false;
    }
    else
    {
        Treasure t = getTreasureFromUI();
        QFile f(filePath);
        f.open(QIODevice::WriteOnly);
        QDataStream out(&f);
        out<<t;
        f.close();

        int idx1 = filePath.lastIndexOf("/");
        int idx2 = filePath.lastIndexOf(".");

        filePath.replace(idx1+1,idx2-idx1-1,ui->lineEdit_treasure_name->text());
        f.rename(filePath);
        return true;
    }
}

void TreasureWidget::clearUI()
{
    ui->lineEdit_treasure_id->clear();
    ui->lineEdit_treasure_name->clear();
    ui->plainTextEdit_treasure_description->clear();

    ui->lineEdit_treasure_maxAtkAddonMin->clear();
    ui->lineEdit_treasure_maxAtkAddonMax->clear();
    ui->lineEdit_treasure_minAtkAddonMin->clear();
    ui->lineEdit_treasure_minAtkAddonMax->clear();
    ui->lineEdit_treasure_maxDefAddonMin->clear();
    ui->lineEdit_treasure_maxDefAddonMax->clear();
    ui->lineEdit_treasure_minDefAddonMin->clear();
    ui->lineEdit_treasure_minDefAddonMax->clear();
    ui->lineEdit_treasure_maxAtkProAddonMin->clear();
    ui->lineEdit_treasure_maxAtkProAddonMax->clear();
    ui->lineEdit_treasure_maxDefProAddonMin->clear();
    ui->lineEdit_treasure_maxDefProAddonMax->clear();

    for(int i=0;i<ui->tableWidget_treasure_fragment->rowCount();i++)
    {
        for(int j=0;j<ui->tableWidget_treasure_fragment->columnCount();j++)
        {
            if(ui->tableWidget_treasure_fragment->item(i,j))
                delete (ui->tableWidget_treasure_fragment->takeItem(i,j));
        }
    }
}

void TreasureWidget::exportToBinary(QString workspacepath)
{
    //export treasure
    QFile f6(workspacepath+"/"+TREASURE_EXPORT_NAME);
    f6.open(QIODevice::WriteOnly);
    QDataStream out6(&f6);

    out6<<Treasure::magic;
    out6<<Treasure::version;

    QDir dir_treasure(workspacepath+"/"+TREASURE_STR);
    QString mfilter = QString("*")+QString(TREASURE_FILE_SUFFIX);
    QStringList treasureList = dir_treasure.entryList(QStringList(mfilter));
    for(int i=0;i<treasureList.length();i++)
    {
        Treasure t;
        QFile f61(dir_treasure.absolutePath()+"/"+treasureList.at(i));
        f61.open(QIODevice::ReadOnly);
        QDataStream in(&f61);
        in>>t;
        out6<<t;
        f61.close();
    }

    f6.close();
}

void TreasureWidget::exportToXML(QString workspacepath)
{
    //*****write XML*******//
    QFile file(workspacepath+"/output/treasure.xml");
    file.open(QIODevice::WriteOnly);
    QDomDocument doc;
    QDomText text;
    QDomProcessingInstruction instruction;
    instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"gb18030\"");
    doc.appendChild(instruction);
    QDomElement root=doc.createElement("root");
    doc.appendChild(root);

    QDir dir_treasure(workspacepath+"/"+TREASURE_STR);
    QStringList treasureList = dir_treasure.entryList(QStringList()<<(QString("*")+TREASURE_FILE_SUFFIX));
    int cnt = treasureList.length();
    for(int i=0;i<cnt;i++)
    {

        QDomElement treasure=doc.createElement("treasure");
        root.appendChild(treasure);

        Treasure e;
        QFile mf(dir_treasure.absolutePath()+"/"+treasureList.at(i));
        mf.open(QIODevice::ReadOnly);
        QDataStream in(&mf);
        in>>e;
        mf.close();

        QDomElement element;

        element=doc.createElement("id");
        text=doc.createTextNode(QString::number(e.id));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("name");
        text=doc.createTextNode(e.name);
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("description");
        text=doc.createTextNode(e.description);
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_attack_addon_min");
        text=doc.createTextNode(QString::number(e.max_attack_addon_min));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_attack_addon_max");
        text=doc.createTextNode(QString::number(e.max_attack_addon_max));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("min_attack_addon_min");
        text=doc.createTextNode(QString::number(e.min_attack_addon_min));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("min_attack_addon_max");
        text=doc.createTextNode(QString::number(e.min_attack_addon_max));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_defense_addon_min");
        text=doc.createTextNode(QString::number(e.max_defense_addon_min));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_defense_addon_max");
        text=doc.createTextNode(QString::number(e.max_defense_addon_max));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("min_defense_addon_min");
        text=doc.createTextNode(QString::number(e.min_defense_addon_min));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("min_defense_addon_max");
        text=doc.createTextNode(QString::number(e.min_defense_addon_max));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_attack_probability_min");
        text=doc.createTextNode(QString::number(e.max_attack_probability_min));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_attack_probability_max");
        text=doc.createTextNode(QString::number(e.max_attack_probability_max));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_defense_probability_min");
        text=doc.createTextNode(QString::number(e.max_defense_probability_min));
        element.appendChild(text);
        treasure.appendChild(element);

        element=doc.createElement("max_defense_probability_max");
        text=doc.createTextNode(QString::number(e.max_defense_probability_max));
        element.appendChild(text);
        treasure.appendChild(element);

        for(int l=0;l<e.needed_Fragments_count;l++)
        {
            QDomElement fragmentsElement=doc.createElement("needed_Fragments");
            treasure.appendChild(fragmentsElement);

            QDomElement tmp;
            tmp=doc.createElement("id");
            text=doc.createTextNode(QString::number(e.needed_Fragments[l].id));
            tmp.appendChild(text);
            fragmentsElement.appendChild(tmp);

            tmp=doc.createElement("count");
            text=doc.createTextNode(QString::number(e.needed_Fragments[l].count));
            tmp.appendChild(text);
            fragmentsElement.appendChild(tmp);
        }
    }

    QTextStream out(&file);
    doc.save(out,4);
    file.close();
}

void TreasureWidget::importFromXML(QString workspacepath,QString xmlFile)
{

}

void TreasureWidget::initialMap()
{
    fragmentMap.clear();

    //initial fragmentMap
    QDir dir_fragment(workPath+"/"+FRAGMENT_STR);
    QString mfilter =  QString("*")+QString(FRAGMENT_FILE_SUFFIX);
    QStringList fragmentList = dir_fragment.entryList(QStringList()<<mfilter);
    Fragment fragment;
    for(int i=0;i<fragmentList.length();i++)
    {
        QFile f(dir_fragment.absolutePath()+"/"+fragmentList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>fragment;
        fragmentMap.insert((int)fragment.id,fragment.name);
        f.close();
    }
}

void TreasureWidget::addTreeItems(QList<QTreeWidgetItem*> items)
{
    for(int i=0;i<ui->treeWidget_treasure_fragment->invisibleRootItem()->childCount();i++)
    {
        QTreeWidgetItem* tmp = ui->treeWidget_treasure_fragment->invisibleRootItem()->child(i);
        ui->treeWidget_treasure_fragment->invisibleRootItem()->removeChild(tmp);
        delete tmp;
    }
    int cnt = items.length();
    for(int i=0;i<cnt;i++)
    {
        QTreeWidgetItem* tmp = items.at(i);
        ui->treeWidget_treasure_fragment->invisibleRootItem()->addChild(tmp->clone());
    }
}


//*************slot functions*************//
void TreasureWidget::s_fragmentItemDoubleClicked(QTreeWidgetItem *item, int col)
{
    int cnt = 0;
    while(ui->tableWidget_treasure_fragment->item(cnt,0))
    {
        if(ui->tableWidget_treasure_fragment->item(cnt,0)->text().replace(" ","").isEmpty())
            break;
        cnt++;
    }

    QString itemText = item->text(col).replace(QString(FRAGMENT_FILE_SUFFIX),"");
    ui->tableWidget_treasure_fragment->setItem(cnt,0,new QTableWidgetItem(itemText));
    ui->tableWidget_treasure_fragment->setItem(cnt,1,new QTableWidgetItem(QString::number((int)fragmentMap.key(itemText))));
}

void TreasureWidget::s_cellDoubleClicked(int row, int column)
{
    if(column==0||column==1)
    {
        delete (ui->tableWidget_treasure_fragment->takeItem(row,0));
        delete (ui->tableWidget_treasure_fragment->takeItem(row,1));
        delete (ui->tableWidget_treasure_fragment->takeItem(row,2));
    }
}
